﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
using Infragistics.WebUI.UltraWebGrid;
using uMES.LeanManufacturing.Common;
using System.IO;
using uMES.LeanManufacturing.ReportBusiness;
using uMES.LeanManufacturing.ParameterDTO;
using System.Text;
using System.Text.RegularExpressions;
using uMES.LeanManufacturing.DBUtility;
using System.Drawing;
using System.Data.OracleClient;
using Infragistics.WebUI.UltraWebNavigator;

public partial class ContainerPlatoonView4Form : System.Web.UI.Page
{
    const string QueryWhere = "ContainerPlatoonView4Form";
    uMESCommonBusiness common = new uMESCommonBusiness();
    uMESContainerPlatoonBusiness bll = new uMESContainerPlatoonBusiness();
    uMESProductTreeViewBusiness productTreeBal = new uMESProductTreeViewBusiness();
    uMESContainerBusiness containerBal = new uMESContainerBusiness();
    int m_PageSize = 10;

    protected void Page_Load(object sender, EventArgs e)
    {
        uMESMasterPage master = this.Master as uMESMasterPage;
        master.strNavigation = "当前位置：预派工信息浏览";
        master.strTitle = "预派工信息浏览";
        master.ChangeFrame(true);
        NormalReportControl normalCntrl = new NormalReportControl();

        
        upageTurning.PageIndexChanged += new pageTurning.PageIndexChangedEventHandler(() => { QueryData(upageTurning.CurrentPageIndex); });
        getProductInfo.DDlProductDataChanged += new GetProductInfo_ascx.DDlProductDataChangedEventHandler(() => { ProductTreeSearch(); });
        if (!IsPostBack)
        {
            txtStartDate.Value = DateTime.Now.AddMonths(-1).ToString("yyyy-MM-dd");
            txtEndDate.Value = DateTime.Now.AddMonths(1).ToString("yyyy-MM-dd");
            AddColumns();
            ClearMessage();
            getProductInfo.GetProductControlDiv.Style["width"] = "190px";
            getProductInfo.GetSearchBtn.Visible = false;
        }
    }


    #region 重置
    protected void btnReSet_Click(object sender, EventArgs e)
    {
        ResetData();
    }

    void ResetData() {
        ShowStatusMessage("", true);
        hdScanCon.Value = string.Empty;
        txtScan.Text = string.Empty;
        txtProcessNo.Text = string.Empty;
        txtContainerName.Text = string.Empty;
        txtProductName.Text = string.Empty;
        txtSpecName.Text = string.Empty;
        //txtStartDate.Value = "";
       // txtEndDate.Value = "";
        wgResult.Rows.Clear();
        wgResult.Columns.Clear();
        txtSrTreeProcessNo.Text = "";
        txtSrTreeProduct.Text = "";
        upageTurning.TotalRowCount = 0;
        AddColumns();
    }
    #endregion
    public Dictionary<string, string> GetQuery()
    {
        string strScanContainerName = txtScan.Text.Trim();
        string strProcessNo = txtProcessNo.Text.Trim();
        string strContainerName = txtContainerName.Text.Trim();
        string strProductName = txtProductName.Text.Trim();
        string strSpecName = txtSpecName.Text.Trim();
        string strStartDate = txtStartDate.Value.Trim();
        string strEndDate = txtEndDate.Value.Trim();
        string strState = ddlStatus.SelectedValue;

        if (strStartDate == string.Empty)
        {
            ShowStatusMessage("请选择开始日期", false);
            return null;
        }

        if (strEndDate == string.Empty)
        {
            ShowStatusMessage("请选择截止日期", false);
            return null;
        }

        DateTime dtStartDate = Convert.ToDateTime(strStartDate);
        DateTime dtEndDate = Convert.ToDateTime(strEndDate);

        if (dtStartDate > dtEndDate)
        {
            ShowStatusMessage("截止日期应晚于开始日期", false);
            return null;
        }

        TimeSpan ts = dtEndDate.Subtract(dtStartDate);

        int Days = ts.Days + 1;

        Dictionary<string, string> result = new Dictionary<string, string>();
        result.Add("Days", Days.ToString());
        if (!string.IsNullOrEmpty(hdScanCon.Value))
        {
            result.Add("ScanContainerName", hdScanCon.Value);
            result.Add("StartDate", strStartDate);
            result.Add("EndDate", strEndDate);
        }
        else
        {
            result.Add("ProcessNo", strProcessNo);
            result.Add("ContainerName", strContainerName);
            result.Add("ProductName", strProductName);
            result.Add("SpecName", strSpecName);
            result.Add("StartDate", strStartDate);
            result.Add("EndDate", strEndDate);
            result.Add("State", strState);
        }

        return result;
    }

    protected void txtScan_TextChanged(object sender, EventArgs e)
    {
        ShowStatusMessage("", true);

        try
        {
            string strScan = txtScan.Text.Trim();
            txtScan.Text = "";
            hdScanCon.Value = string.Empty;
            if (strScan != string.Empty)
            {
                hdScanCon.Value = strScan;
                QueryData(1);
            }
        }
        catch (Exception ex)
        {
            ShowStatusMessage(ex.Message, false);
        }
    }

    public void QueryData(int intIndex)
    {
        try
        {

            Dictionary<string, string> para = GetQuery();
            upageTurning.Enabled();
            if (para == null)
            {
                return;
            }

            ShowStatusMessage("", true);
            uMESPagingDataDTO result = bll.GetAPSMainInfo(para, intIndex, m_PageSize);
            wgResult.Rows.Clear();
            wgResult.Columns.Clear();

            Drawing(result.DBset, intIndex);

            //给分页控件赋值，用于分页控件信息显示
            this.upageTurning.TotalRowCount = int.Parse(result.RowCount);
            this.upageTurning.RowCountByPage = m_PageSize;
        }
        catch (Exception e)
        {
            ShowStatusMessage(e.Message, false);
        }

    }

    /// <summary>
    /// 绘制零件进度表显示界面
    /// </summary>
    /// <param name="ds"></param>
    void Drawing(DataSet ds,int intIndex)
    {
        DataTable disDt = new DataTable();
        disDt.Columns.Add("SeqNumber");//序号
        disDt.Columns.Add("ProcessNo");//工作令号
        disDt.Columns.Add("OprNo");//作业令号
        disDt.Columns.Add("ProductName");//图号
        disDt.Columns.Add("Description");//名称
        disDt.Columns.Add("ContainerName");//批次号
        disDt.Columns.Add("Qty");//批次数量
        disDt.Columns.Add("isSpec");//是否是工序
        disDt.Columns.Add("CurrentSpec");//当前工序
        disDt.Columns.Add("ContainerID");
        disDt.Columns.Add("State");
        disDt.Columns.Add("OrderCompDate");
        disDt.Columns.Add("RealCompDate");
        disDt.Columns.Add("ProductID");
        disDt.Columns.Add("WorkflowID");
        disDt.Columns.Add("ContainerComments");

        //创建Grid列
        AddColumns();

        //主信息
        DataTable dtMain = ds.Tables[0];

        //详细信息
        DataTable dtDetail = ds.Tables[1];
        Session["PlatoonDetail"] = dtDetail;

        DataTable dtRGGS = ds.Tables[2];
        Session["PlatoonRGGS"] = dtRGGS;

        #region 获取设备组状态

        DateTime beginDate = DateTime.MaxValue;

        foreach (DataRow row in dtDetail.Rows)
        {
            if (Convert.ToDateTime(row["PlannedStartDate"].ToString()) < beginDate)
            {
                beginDate = Convert.ToDateTime(row["PlannedStartDate"].ToString());
            }
        }

        DateTime endDate = DateTime.MinValue;

        foreach (DataRow row in dtDetail.Rows)
        {
            if (Convert.ToDateTime(row["PlannedCompletionDate"].ToString()) > endDate)
            {
                endDate = Convert.ToDateTime(row["PlannedCompletionDate"].ToString());
            }
        }

        DataTable dtRGStatus = bll.GetResourceGroupStatus(beginDate, endDate);

        foreach (DataRow row in dtDetail.Rows)
        {
            string strRGID = row["ResourceGroupID"].ToString();
            string strSDate = Convert.ToDateTime(row["PlannedStartDate"].ToString()).ToString("yyyy-MM-dd");
            string strEDate = Convert.ToDateTime(row["PlannedCompletionDate"].ToString()).ToString("yyyy-MM-dd");

            string strFilter = string.Format("RGID = '{0}' AND RGDate >= '{1}' AND RGDate <= '{2}' AND RGStatus = 1", strRGID, strSDate, strEDate);

            DataRow[] rows = dtRGStatus.Select(strFilter);

            if (rows.Length > 0)
            {
                row["state"] = "1";
            }
        }

        #endregion

        //最大列值
        int maxColum = 0;

        if (dtDetail.Rows.Count > 0)
        {
            foreach (DataRow dr in dtMain.Rows)
            {
                string strFilter = String.Format("ContainerID = '{0}' ", dr["ContainerID"].ToString());

                DataRow[] rows = dtDetail.Select(strFilter);

                if (maxColum < rows.Length)
                {
                    maxColum = rows.Length;
                }
            }
        }

        //创建工序列
        for (int i = 1; i <= maxColum; i++)
        {
            disDt.Columns.Add("A" + i.ToString().Trim());
        }

        //创建Grid工序列
        UltraGridColumn colum = new UltraGridColumn();
        for (int i = 1; i <= maxColum; i++)
        {
            colum = new UltraGridColumn("A" + i.ToString(), " ", ColumnType.NotSet, "");
            colum.BaseColumnName = "A" + i.ToString();
            colum.Key = "A" + i.ToString();
            colum.Width = 100;
            colum.HeaderStyle.Height = 20;
            colum.HeaderStyle.HorizontalAlign = HorizontalAlign.Center;
            wgResult.Bands[0].Columns.Add(colum);
        }

        //disDt赋值
        int rowindex = 0;
        int pageSize = m_PageSize;
        int pageIndex = intIndex;

        foreach (DataRow drMain in dtMain.Rows)
        {
            Dictionary<string, string> userInfo = Session["UserInfo"] as Dictionary<string, string>;
            string strEmployeeID = userInfo["EmployeeID"];

            string strMfgManagerID = drMain["MfgManagerID"].ToString();

            if (strMfgManagerID == strEmployeeID)
            {
                rowindex += 1;
                DataRow[] drInsrt;
                DataRow rowTmp = disDt.NewRow();
                rowTmp["SeqNumber"] = pageSize * (pageIndex - 1) + rowindex;
                rowTmp["ProcessNo"] = drMain["ProcessNo"];//工作令号
                rowTmp["OprNo"] = drMain["OprNo"];//作业令号
                rowTmp["ProductName"] = drMain["ProductName"];//图号
                rowTmp["Description"] = drMain["Description"];//名称

                rowTmp["ContainerName"] = string.Format("<a href='Custom/BwPlanManager/BwSynergicInfoApplyForm.aspx?ContainerName={0}' style='font-size: small;height:10px;text-align: center;color:Blue;'>{0}</a>", drMain["ContainerName"]);//批次号

                rowTmp["ContainerID"] = drMain["ContainerID"];
                rowTmp["State"] = drMain["State"];
                rowTmp["Qty"] = drMain["Qty"];//批次数量
                rowTmp["isSpec"] = "1";
                rowTmp["RealCompDate"] = drMain["RealCompDate"];

                if (drMain["OrderCompDate"].ToString() != string.Empty)
                {
                    rowTmp["OrderCompDate"] = Convert.ToDateTime(drMain["OrderCompDate"]).ToString("yyyy-MM-dd");
                }
                else
                {
                    rowTmp["OrderCompDate"] = "";
                }
                rowTmp["ProductID"] = drMain["ProductID"];
                rowTmp["WorkflowID"] = drMain["WorkflowID"];
                rowTmp["ContainerComments"] = drMain["ContainerComments"];

                disDt.Rows.Add(rowTmp);

                rowTmp = disDt.NewRow();
                rowTmp["SeqNumber"] = "";
                rowTmp["ProcessNo"] = "";//工作令号
                rowTmp["OprNo"] = "";//作业令号
                rowTmp["ProductName"] = "";//图号
                rowTmp["Description"] = "";//名称
                rowTmp["ContainerName"] = "";//批次号
                rowTmp["Qty"] = "";//批次数量
                rowTmp["ProductID"] = drMain["ProductID"];
                rowTmp["WorkflowID"] = drMain["WorkflowID"];
                disDt.Rows.Add(rowTmp);

                string strConName = drMain["ContainerName"].ToString();
                string strConID = drMain["ContainerID"].ToString();

                drInsrt = dtDetail.Select("ContainerID = '" + strConID + "'", "SpecSequence");

                for (int h = 0; h < drInsrt.Length; h++)
                {
                    string strSpecName = drInsrt[h]["SpecName"].ToString();
                    string strDispatchinfoName = drInsrt[h]["dispatchinfoname"].ToString();
                    string strDispatchinfoID = drInsrt[h]["ID"].ToString();
                    string strIsWX = drInsrt[h]["IsWX"].ToString();

                    string strSDate = FormatDateTime(Convert.ToDateTime(drInsrt[h]["PlannedStartDate"].ToString()).ToString("yyyy-MM-dd HH:mm"));
                    string strEDate = FormatDateTime(Convert.ToDateTime(drInsrt[h]["PlannedCompletionDate"].ToString()).ToString("yyyy-MM-dd HH:mm"));

                    disDt.Rows[disDt.Rows.Count - 2]["A" + (h + 1).ToString()] = "<a href='#' onclick =openSpecDetailwins('" + strDispatchinfoID + "')  style='font-size: small;height:10px;text-align: center;color:Blue;'>" + common.GetSpecNameFromSpecName(strSpecName) + "</a><br /><div style=\"font - size:10px; \">" + strSDate + " - " + strEDate + "</div>";

                    //状态
                    string strState = "0";
                    if (!string.IsNullOrEmpty(drInsrt[h]["state"].ToString()))
                    {
                        strState = drInsrt[h]["state"].ToString();
                    }

                    string strRGName = drInsrt[h]["ResourceGroupName"].ToString();
                    string strRGID = drInsrt[h]["ResourceGroupID"].ToString();

                    //是否外协
                    string strIsSynergic = drInsrt[h]["IsSynergic"].ToString();

                    disDt.Rows[disDt.Rows.Count - 1]["A" + (h + 1).ToString()] = strRGName + "," + strRGID + "," + strState + "," + strIsWX + "," + strIsSynergic;
                }
            }
        }

        wgResult.DataSource = disDt;
        wgResult.DataBind();
    }

    protected string FormatDateTime(string date)
    {
        DateTime dateTime = Convert.ToDateTime(date);

        if (dateTime.Hour > 12)
        {
            dateTime = dateTime.AddDays(1);
        }

        return dateTime.ToString("yy.MM.dd");
    }

    protected void wgResult_DataBound(object sender, EventArgs e)
    {
        for (int i = 0; i < wgResult.Rows.Count; i++)
        {
            if (!string.IsNullOrEmpty(wgResult.Rows[i].Cells.FromKey("isspec").Text))
            {
                if (wgResult.Rows[i].Cells.FromKey("isspec").Text == "1")
                {
                    string strState = wgResult.Rows[i].Cells.FromKey("State").Value.ToString();

                    if (strState == "1") //已下发
                    {
                        wgResult.Rows[i].Cells.FromKey("State").Style.BackColor = Color.LightSeaGreen;
                        wgResult.Rows[i].Cells.FromKey("State").Text = "";

                        wgResult.Rows[i].Cells.FromKey("ckSelect").AllowEditing = AllowEditing.No;
                    }
                    else if (strState == "10") // 已审核通过
                    {
                        wgResult.Rows[i].Cells.FromKey("State").Style.BackColor = Color.LightGreen;
                        wgResult.Rows[i].Cells.FromKey("State").Text = "";

                        wgResult.Rows[i].Cells.FromKey("ckSelect").AllowEditing = AllowEditing.Yes;
                    }
                    else if (strState == "20") // 审核未通过
                    {
                        wgResult.Rows[i].Cells.FromKey("State").Style.BackColor = Color.LightYellow;
                        wgResult.Rows[i].Cells.FromKey("State").Text = "";

                        wgResult.Rows[i].Cells.FromKey("ckSelect").AllowEditing = AllowEditing.No;
                    }
                    else //未审核
                    {
                        wgResult.Rows[i].Cells.FromKey("State").Style.BackColor = Color.LightSkyBlue;
                        wgResult.Rows[i].Cells.FromKey("State").Text = "";

                        wgResult.Rows[i].Cells.FromKey("ckSelect").AllowEditing = AllowEditing.No;
                    }

                    try
                    {
                        string strOrderCompDate = wgResult.Rows[i].Cells.FromKey("OrderCompDate").Value.ToString();
                        string strRealCompDate = wgResult.Rows[i].Cells.FromKey("RealCompDate").Value.ToString();

                        if (Convert.ToDateTime(strRealCompDate) >= Convert.ToDateTime(strOrderCompDate).AddDays(1))
                        {
                            wgResult.Rows[i].Cells.FromKey("OrderCompDate").Style.ForeColor = Color.Red;
                        }
                    }
                    catch
                    { }

                    continue;
                }
            }

            wgResult.Rows[i].Cells.FromKey("ckSelect").AllowEditing = AllowEditing.No;

            for (int j = 0; j < wgResult.Columns.Count; j++)
            {
                if (wgResult.Columns[j].BaseColumnName.Contains("A"))
                {
                    if (!string.IsNullOrEmpty(wgResult.Rows[i].Cells[j].Text))
                    {
                        string strTmp = wgResult.Rows[i].Cells[j].Text;
                        string[] array = strTmp.Split(',');

                        wgResult.Rows[i].Cells[j].Text = "<a href='#' onclick =openRGDetailwins('" + array[1] + "')  style='font-size: small;height:10px;text-align: center;color:Blue;'>" + array[0] + "</a>";

                        if (array[2] == "1")
                        {
                            wgResult.Rows[i].Cells[j].Style.BackColor = Color.Red;
                            //wgResult.Rows[i].Cells[j].Text = array[0];
                        }
                        else
                        {
                            wgResult.Rows[i].Cells[j].Style.BackColor = Color.Green;
                            //wgResult.Rows[i].Cells[j].Text = array[0];
                        }

                        if (array[3] == "1" || array[4] == "1")
                        {
                            wgResult.Rows[i - 1].Cells[j].Style.BackColor = Color.Yellow;
                        }
                    }
                }
            }
        }
    }

    #region 创建Grid列
    /// <summary>
    /// 创建Grid列
    /// </summary>
    void AddColumns()
    {
        UltraGridColumn colum = new UltraGridColumn("ckSelect", "选择", ColumnType.CheckBox, "");
        //colum.BaseColumnName = "ckSelect";
        colum.Key = "ckSelect";
        colum.Width = 40;
        colum.Hidden = false;
        colum.HeaderStyle.Height = 20;
        colum.HeaderStyle.HorizontalAlign = HorizontalAlign.Center;
        colum.AllowUpdate = AllowUpdate.Yes;
        //colum.Header.Fixed = true;
        wgResult.Bands[0].Columns.Add(colum);

        colum = new UltraGridColumn("ContainerID", "ContainerID", ColumnType.NotSet, "");
        colum.BaseColumnName = "ContainerID";
        colum.Key = "ContainerID";
        colum.Width = 120;
        colum.Hidden = true;
        colum.HeaderStyle.Height = 20;
        colum.HeaderStyle.HorizontalAlign = HorizontalAlign.Center;
        colum.Header.Fixed = true;
        wgResult.Bands[0].Columns.Add(colum);

        colum = new UltraGridColumn("xuhao", "序号", ColumnType.NotSet, "");
        colum.BaseColumnName = "Seqnumber";
        colum.Key = "Seqnumber";
        colum.Width = 40;
        colum.Hidden = false;
        colum.HeaderStyle.Height = 20;
        colum.HeaderStyle.HorizontalAlign = HorizontalAlign.Center;
        colum.Header.Fixed = true;
        wgResult.Bands[0].Columns.Add(colum);

        colum = new UltraGridColumn("State", "", ColumnType.NotSet, "");
        colum.BaseColumnName = "State";
        colum.Key = "State";
        colum.Width = 40;
        colum.Hidden = false;
        colum.HeaderStyle.Height = 20;
        colum.HeaderStyle.HorizontalAlign = HorizontalAlign.Center;
        colum.Header.Fixed = true;
        wgResult.Bands[0].Columns.Add(colum);

        colum = new UltraGridColumn("processno", "工作令号", ColumnType.NotSet, "");
        colum.BaseColumnName = "processno";
        colum.Key = "processno";
        colum.Width = 120;
        colum.Hidden = false;
        colum.HeaderStyle.Height = 20;
        colum.HeaderStyle.HorizontalAlign = HorizontalAlign.Center;
        colum.Header.Fixed = true;
        wgResult.Bands[0].Columns.Add(colum);

        colum = new UltraGridColumn("oprno", "作业令号", ColumnType.NotSet, "");
        colum.BaseColumnName = "oprno";
        colum.Key = "oprno";
        colum.Width = 120;
        colum.Hidden = true;
        colum.HeaderStyle.Height = 20;
        colum.HeaderStyle.HorizontalAlign = HorizontalAlign.Center;
        colum.Header.Fixed = true;
        wgResult.Bands[0].Columns.Add(colum);

        colum = new UltraGridColumn("productname", "图号", ColumnType.NotSet, "");
        colum.BaseColumnName = "productname";
        colum.Key = "productname";
        colum.Width = 120;
        colum.Hidden = false;
        colum.HeaderStyle.Height = 20;
        colum.HeaderStyle.HorizontalAlign = HorizontalAlign.Center;
        colum.Header.Fixed = true;
        wgResult.Bands[0].Columns.Add(colum);

        colum = new UltraGridColumn("description", "名称", ColumnType.NotSet, "");
        colum.BaseColumnName = "description";
        colum.Key = "description";
        colum.Width = 120;
        colum.Hidden = false;
        colum.HeaderStyle.Height = 20;
        colum.HeaderStyle.HorizontalAlign = HorizontalAlign.Center;
        colum.Header.Fixed = true;
        wgResult.Bands[0].Columns.Add(colum);

        colum = new UltraGridColumn("containername", "批次号", ColumnType.NotSet, "");
        colum.BaseColumnName = "containername";
        colum.Key = "containername";
        colum.Width = 120;
        colum.Hidden = false;
        colum.HeaderStyle.Height = 20;
        colum.HeaderStyle.HorizontalAlign = HorizontalAlign.Center;
        colum.Header.Fixed = true;
        wgResult.Bands[0].Columns.Add(colum);

        colum = new UltraGridColumn("qty", "数量", ColumnType.NotSet, "");
        colum.BaseColumnName = "qty";
        colum.Key = "qty";
        colum.Width = 60;
        colum.Hidden = false;
        colum.HeaderStyle.Height = 20;
        colum.HeaderStyle.HorizontalAlign = HorizontalAlign.Center;
        colum.Header.Fixed = true;
        wgResult.Bands[0].Columns.Add(colum);

        colum = new UltraGridColumn("IsSpec", "IsSpec", ColumnType.NotSet, "");
        colum.BaseColumnName = "IsSpec";
        colum.Key = "IsSpec";
        colum.Width = 60;
        colum.Hidden = true;
        colum.HeaderStyle.Height = 20;
        colum.HeaderStyle.HorizontalAlign = HorizontalAlign.Center;
        colum.Header.Fixed = true;
        wgResult.Bands[0].Columns.Add(colum);

        colum = new UltraGridColumn("CurrentSpec", "CurrentSpec", ColumnType.NotSet, "");
        colum.BaseColumnName = "CurrentSpec";
        colum.Key = "CurrentSpec";
        colum.Width = 60;
        colum.Hidden = true;
        colum.HeaderStyle.Height = 20;
        colum.HeaderStyle.HorizontalAlign = HorizontalAlign.Center;
        colum.Header.Fixed = true;
        wgResult.Bands[0].Columns.Add(colum);

        colum = new UltraGridColumn("OrderCompDate", "计划完成日期", ColumnType.NotSet, "");
        colum.BaseColumnName = "OrderCompDate";
        colum.Key = "OrderCompDate";
        colum.Width = 80;
        colum.HeaderStyle.HorizontalAlign = HorizontalAlign.Center;
        wgResult.Bands[0].Columns.Add(colum);

        colum = new UltraGridColumn("RealCompDate", "RealCompDate", ColumnType.NotSet, "");
        colum.BaseColumnName = "RealCompDate";
        colum.Key = "RealCompDate";
        colum.Width = 80;
        colum.Hidden = true;
        colum.HeaderStyle.HorizontalAlign = HorizontalAlign.Center;
        wgResult.Bands[0].Columns.Add(colum);

        colum = new UltraGridColumn("WorkflowID", "WorkflowID", ColumnType.NotSet, "");
        colum.BaseColumnName = "WorkflowID";
        colum.Key = "WorkflowID";
        colum.Width = 60;
        colum.Hidden = true;
        colum.HeaderStyle.Height = 20;
        colum.HeaderStyle.HorizontalAlign = HorizontalAlign.Center;
        colum.Header.Fixed = true;
        wgResult.Bands[0].Columns.Add(colum);

        colum = new UltraGridColumn("ProductID", "ProductID", ColumnType.NotSet, "");
        colum.BaseColumnName = "ProductID";
        colum.Key = "ProductID";
        colum.Width = 60;
        colum.Hidden = true;
        colum.HeaderStyle.Height = 20;
        colum.HeaderStyle.HorizontalAlign = HorizontalAlign.Center;
        colum.Header.Fixed = true;
        wgResult.Bands[0].Columns.Add(colum);

        colum = new UltraGridColumn("containercomments", "审核意见", ColumnType.NotSet, "");
        colum.BaseColumnName = "containercomments";
        colum.Key = "containercomments";
        colum.Width = 120;
        colum.Hidden = false;
        colum.HeaderStyle.Height = 20;
        colum.HeaderStyle.HorizontalAlign = HorizontalAlign.Left;
        colum.Header.Fixed = true;
        wgResult.Bands[0].Columns.Add(colum);
    }
    #endregion

    public void ResetQuery()
    {
        ShowStatusMessage("", true);

        Session[QueryWhere] = "";
        txtScan.Text = string.Empty;
        txtProcessNo.Text = string.Empty;
        txtContainerName.Text = string.Empty;
        txtProductName.Text = string.Empty;
        txtSpecName.Text = string.Empty;
        txtStartDate.Value = string.Empty;
        txtEndDate.Value = string.Empty;
        wgResult.Rows.Clear();
        upageTurning.TotalRowCount = 0;
    }

    #region 提示信息
    /// <summary>
    /// 提示信息
    /// </summary>
    /// <param name="strMessage"></param>
    /// <param name="boolResult"></param>
    protected void ShowStatusMessage(string strMessage, Boolean boolResult)
    {
        string strScript = "<script>ShowMessage(\"" + strMessage + "\", " + boolResult.ToString().ToLower() + ");</script>";
        // ClientScript.RegisterStartupScript(GetType(), "", strScript);
        Infragistics.WebUI.Shared.CallBackManager.AddScriptBlock(Page, WebAsyncRefreshPanel1, strScript);
    }
    #endregion

    #region 清除提示信息
    protected void ClearMessage()
    {
        string strScript = "<script>ShowMessage(\"" + "" + "\", 'true');</script>";
        LiteralControl child = new LiteralControl(strScript);
        WebAsyncRefreshPanel1.Controls.Add(child);
    }
    #endregion

    protected void btnSearch_Click(object sender, EventArgs e)
    {
        try
        {
            try
            {
                upageTurning.TxtCurrentPageIndex.Text = "1";
                Session["CurrenIndex"] = null;
                hdScanCon.Value = string.Empty;
                QueryData(upageTurning.CurrentPageIndex);
            }
            catch (Exception ex)
            {
                ShowStatusMessage(ex.Message, false);
            }
        }
        catch (Exception ex)
        {
            ShowStatusMessage(ex.Message, false);
        }
    }

    protected void btnAPS_Click(object sender, EventArgs e)
    {
        //ShowStatusMessage("", false);

        try
        {
            List<string> listContainerID = new List<string>();

            for (int i = 0; i < wgResult.Rows.Count; i++)
            {
                string ck = wgResult.Rows[i].Cells.FromKey("ckSelect").Value.ToString();

                if (ck.ToUpper() == "TRUE")
                {
                    if (wgResult.Rows[i].Cells.FromKey("ContainerID").Value != null)
                    {
                        string strContainerID = wgResult.Rows[i].Cells.FromKey("ContainerID").Value.ToString();

                        listContainerID.Add(strContainerID);
                    }
                }
            }

            if (listContainerID.Count == 0)
            {
                ShowStatusMessage("请选择要下发的批次", false);
                return;
            }

            bll.UpdateDIState(listContainerID, 1, "");

            int intIndex = 1;
            if (upageTurning.TxtCurrentPageIndex.Text!=null)
            {
                intIndex = Convert.ToInt32(upageTurning.TxtCurrentPageIndex.Text);
            }
            Session["CurrenIndex"] = upageTurning.TxtCurrentPageIndex.Text;
            QueryData(intIndex);
            Session["CurrenIndex"] = null;
            ShowStatusMessage("下发完成", true);
        }
        catch (Exception ex)
        {
            ShowStatusMessage(ex.Message, false);
        }
    }

    protected void btnSelect1_Click(object sender, EventArgs e)
    {
        try
        {
            string strTxt = btnSelect1.Text;
            for (int i = 0; i < wgResult.Rows.Count; i++)
            {
                if (wgResult.Rows[i].Cells.FromKey("ckSelect").AllowEditing == AllowEditing.Yes)
                {

                    if (strTxt == "全选")
                    {
                        wgResult.Rows[i].Cells.FromKey("ckSelect").Value = true;
                    }
                    else if (strTxt == "全不选")
                    {
                        wgResult.Rows[i].Cells.FromKey("ckSelect").Value = false;
                    }
                }
            }

            if (strTxt == "全选")
            {
                btnSelect1.Text = "全不选";
            }
            else if (strTxt == "全不选")
            {
                btnSelect1.Text = "全选";
            }
        }
        catch (Exception ex)
        {
            ShowStatusMessage(ex.Message, false);
        }
    }

    protected void btnSelect2_Click(object sender, EventArgs e)
    {
        try
        {
            for (int i = 0; i < wgResult.Rows.Count; i++)
            {

                if (wgResult.Rows[i].Cells.FromKey("ckSelect").AllowEditing == AllowEditing.Yes)
                {
                    string ck = wgResult.Rows[i].Cells.FromKey("ckSelect").Value.ToString();

                    if (ck.ToUpper() == "TRUE")
                    {
                        wgResult.Rows[i].Cells.FromKey("ckSelect").Value = false;
                    }
                    else
                    {
                        wgResult.Rows[i].Cells.FromKey("ckSelect").Value = true;
                    }
                }
            }
        }
        catch (Exception ex)
        {
            ShowStatusMessage(ex.Message, false);
        }
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        try
        {
            ClearMessage();

            UltraGridRow uldr = wgResult.DisplayLayout.ActiveRow;
            if (uldr == null)
            {
                ShowStatusMessage("请选择订单记录", false);
                //Infragistics.WebUI.Shared.CallBackManager.AddScriptBlock(Page, WebAsyncRefreshPanel1, "<script>alert('请选择批次记录')</script>");
                return;
            }

            DataTable poupDt = new DataTable();
            poupDt.Columns.Add("ProductID");
            poupDt.Columns.Add("WorkflowID"); poupDt.Columns.Add("ContainerID"); poupDt.Columns.Add("ContainerName");
            DataRow newRow = poupDt.NewRow();
            newRow["ProductID"] = uldr.Cells.FromKey("ProductID").Text;
            newRow["WorkflowID"] = uldr.Cells.FromKey("Workflowid").Text; newRow["ContainerID"] = uldr.Cells.FromKey("ContainerID").Text;
            newRow["ContainerName"] =containerBal.GetTableInfo("container","containerid",newRow["ContainerID"].ToString()).Rows[0]["ContainerName"];
            poupDt.Rows.Add(newRow);
            Session.Add("ProcessDocument", poupDt);
            string strScript = string.Empty;

            strScript = "<script>window.showModalDialog('Custom/bwCommonPage/uMESDocumentViewPopupForm.aspx', '', 'dialogWidth: 700px; dialogHeight: 600px; status = no; center: Yes; resizable: NO; ')</script>";
            Infragistics.WebUI.Shared.CallBackManager.AddScriptBlock(Page, WebAsyncRefreshPanel1, strScript);
        }
        catch (Exception ex)
        {
            ShowStatusMessage(ex.Message, false);
        }
    }


    #region 树形区域 add:Wangjh 20201020


    /// <summary>
    /// 遍历所有子节点，并查询订单
    /// </summary>
    /// <param name="childNodes"></param>
    /// <param name="dt"></param>
    void GetChildNodesData2(Nodes childNodes, DataSet ds)
    {

        foreach (Node node in childNodes)
        {
            DataSet tempDs = QueryData3("",node.Text.ToString());

            ds.Tables["ContainerName"].Merge(tempDs.Tables["ContainerName"]);
            ds.Tables["DetailInfo"].Merge(tempDs.Tables["DetailInfo"]);
            ds.Tables["RGGS"].Merge(tempDs.Tables["RGGS"]);

            GetChildNodesData2(node.Nodes, ds);
        }
    }

    /// <summary>
    /// 查询该产品及其以下所有
    /// </summary>
    void SearchAllData2()
    {
        wgResult.Rows.Clear();
        wgResult.Columns.Clear();

        var selectNode = treeProduct.SelectedNode;
        if (selectNode == null)
        {
            ShowStatusMessage("请先选择节点", false);
            return;
        }
        // selectNode.nod
        DataSet ds = QueryData3("",selectNode.Text.ToString());
        GetChildNodesData2(selectNode.Nodes, ds);

        Drawing(ds, 1);
    }

    protected void btnSearchAll_Click(object sender, EventArgs e)
    {
        try { upageTurning.Disabled(); SearchAllData2(); } catch (Exception ex) { ShowStatusMessage(ex.Message, false); }
    }

    public void QueryData2(string productID, string productName)
    {
        try
        {
            // Dictionary<string, string> para = GetQuery();

            Dictionary<string, string> para = new Dictionary<string, string>();
            para["PageSize"] = m_PageSize.ToString();
            if (!string.IsNullOrWhiteSpace(productID))
                para["ProductID"] = productID;
            if (!string.IsNullOrWhiteSpace(productName))
                para["ProductName2"] = productName;


            if (!string.IsNullOrWhiteSpace(txtTreeProcessNo.Text))
            {
                para["ProcessNo"] = txtTreeProcessNo.Text;
            }

            string strStartDate = txtStartDate.Value.Trim();
            string strEndDate = txtEndDate.Value.Trim();
            if (strStartDate == string.Empty)
            {
                ShowStatusMessage("请选择开始日期", false);
                return;
            }

            if (strEndDate == string.Empty)
            {
                ShowStatusMessage("请选择截止日期", false);
                return;
            }

            DateTime dtStartDate = Convert.ToDateTime(strStartDate);
            DateTime dtEndDate = Convert.ToDateTime(strEndDate);

            if (dtStartDate > dtEndDate)
            {
                ShowStatusMessage("截止日期应晚于开始日期", false);
                return;
            }

            TimeSpan ts = dtEndDate.Subtract(dtStartDate);

            int Days = ts.Days + 1;
            para.Add("Days", Days.ToString());

            uMESPagingDataDTO result = bll.GetAPSMainInfo(para, 1, 100000);
            wgResult.Rows.Clear();
            wgResult.Columns.Clear();

            Drawing(result.DBset, 1);

        }
        catch (Exception e)
        {
            ShowStatusMessage(e.Message, false);
        }

    }

    public DataSet QueryData3(string productID, string productName)
    {
        try
        {
            // Dictionary<string, string> para = GetQuery();
            DataSet re = new DataSet();

            Dictionary<string, string> para = new Dictionary<string, string>();
            para["PageSize"] = m_PageSize.ToString();
            if (!string.IsNullOrWhiteSpace(productID))
                para["ProductID"] = productID;
            if (!string.IsNullOrWhiteSpace(productName))
                para["ProductName2"] = productName;


            if (!string.IsNullOrWhiteSpace(txtTreeProcessNo.Text))
            {
                para["ProcessNo"] = txtTreeProcessNo.Text;
            }

            string strStartDate = txtStartDate.Value.Trim();
            string strEndDate = txtEndDate.Value.Trim();
            if (strStartDate == string.Empty)
            {
                ShowStatusMessage("请选择开始日期", false);
                return re;
            }

            if (strEndDate == string.Empty)
            {
                ShowStatusMessage("请选择截止日期", false);
                return re;
            }

            DateTime dtStartDate = Convert.ToDateTime(strStartDate);
            DateTime dtEndDate = Convert.ToDateTime(strEndDate);

            if (dtStartDate > dtEndDate)
            {
                ShowStatusMessage("截止日期应晚于开始日期", false);
                return re;
            }

            TimeSpan ts = dtEndDate.Subtract(dtStartDate);

            int Days = ts.Days + 1;
            para.Add("Days", Days.ToString());

            uMESPagingDataDTO result = bll.GetAPSMainInfo(para, 1, 100000);
            re = result.DBset;

            return re;
        }
        catch (Exception e)
        {
            ShowStatusMessage(e.Message, false);
            return null;
        }

    }


    protected void treeProduct_NodeSelectionChanged(object sender, WebTreeNodeEventArgs e)
    {
        try
        {
            upageTurning.Disabled();
            ResetData();
            selectProductNode();

        }
        catch (Exception ex) { ShowStatusMessage(ex.Message, false); }

    }

    void selectProductNode()
    {
        // var selectNode = tvTree.SelectedNode;
        // string productID = selectNode.Value;

        var selectNode = treeProduct.SelectedNode;
        string productID = selectNode.Tag.ToString();

        txtSrTreeProduct.Text = selectNode.Text;
        txtSrTreeProcessNo.Text = txtTreeProcessNo.Text;
        QueryData2("",selectNode.Text);
    }


    protected void btnTreeSearch_Click(object sender, EventArgs e)
    {
        ClearMessage();

        try {
            TreeSearchProduct();
           // ProductTreeSearch();
        } catch (Exception ex) { ShowStatusMessage(ex.Message, false); }

    }

    //获取产品名及版本
    void GetProductInfo(ref string productName, ref string productRev)
    {
        string productInfo = getProductInfo.ProducText;

        if (productInfo == "")
        {
            return;
        }

        productName = productInfo.Substring(0, productInfo.IndexOf(":"));
        productRev = productInfo.Substring(productInfo.IndexOf(":") + 1, productInfo.IndexOf("(", productName.Length) - productInfo.IndexOf(":") - 1);

    }

    //UltraWebTree
    Node GetProductTree2(string productName, string productRev, DataTable dt)
    {
        Node productTree = new Node();

        DataRow[] drs = dt.Select(string.Format("productname='{0}' and productrev='{1}'", productName, productRev));


        for (int i = 0; i < drs.Length; i++)
        {
            Node productSubTree = GetProductTree2(drs[i]["subproductname"].ToString(), drs[i]["subproductrev"].ToString(), dt);

            productSubTree.Text = drs[i]["subproductname"].ToString();// + ":" + drs[i]["subproductrev"].ToString(); //+ " | " + drs[i]["subproductstatus"].ToString();
            productSubTree.Tag = drs[i]["subproductid"].ToString();
            productTree.Nodes.Add(productSubTree);
            if (drs[i]["IsCommon"].ToString() == "1")
            {
                productSubTree.Styles.ForeColor =Color.Blue;
                productSubTree.ToolTip = "公共件";
            }
        }

        return productTree;

    }


    /// <summary>
    /// 产品结构树
    /// </summary>
    void ProductTreeSearch()
    {
        treeProduct.Nodes.Clear();

        string productName = "", productRev = "";
        GetProductInfo(ref productName, ref productRev);
        if (string.IsNullOrWhiteSpace(productName))
        {
            ShowStatusMessage("请选择产品", false);
            return;
        }
        if (string.IsNullOrWhiteSpace(txtTreeProcessNo.Text))
        {
            ShowStatusMessage("请选择工作令号", false);
            return;
        }
        Dictionary<string, string> para = new Dictionary<string, string>();
        para.Add("ProductName", productName); para.Add("ProductRev", productRev);
        para.Add("ProcessNo", txtTreeProcessNo.Text);//工作令号
        DataTable dt = productTreeBal.GetSubProductInfo(para);

        if (dt.Rows.Count == 0)
        {
            ShowStatusMessage("此产品没有子级零组件", false);
            return;
        }
        //TreeView
        /*
        TreeNode productTree = GetProductTree(productName, productRev, dt);
        DataRow[] drs = dt.Select(string.Format("productname='{0}' and productrev='{1}'", productName, productRev));
        productTree.Text = drs[0]["productname"].ToString() + ":" + drs[0]["productrev"].ToString(); //+ " | " + drs[0]["productStatus"].ToString();
        productTree.Value = drs[0]["productid"].ToString();
        tvTree.Nodes.Add(productTree);
        tvTree.Nodes[0].Expand();
        */
        //UltraWebTree
        Node productTree = GetProductTree2(productName, productRev, dt);
        DataRow[] drs = dt.Select(string.Format("productname='{0}' and productrev='{1}'", productName, productRev));
        productTree.Text = drs[0]["productname"].ToString();// + ":" + drs[0]["productrev"].ToString(); //+ " | " + drs[0]["productStatus"].ToString();
        productTree.Tag = drs[0]["productid"].ToString();
        treeProduct.Nodes.Add(productTree);
        treeProduct.Nodes[0].Expand(false);
    }

    protected void btnTreeReset_Click(object sender, EventArgs e)
    {
        try
        {
            ResetData();
            txtTreeProcessNo.Text = string.Empty;
            getProductInfo.InitControl();
            treeProduct.Nodes.Clear();
        }
        catch (Exception ex)
        {
            ShowStatusMessage(ex.Message, false);
        }
    }

    /// <summary>
    /// 根据工作令号查询产品
    /// </summary>
    void TreeSearchProduct()
    {
        treeProduct.Nodes.Clear();
        if (string.IsNullOrWhiteSpace(txtTreeProcessNo.Text))
        {
            ShowStatusMessage("请选择工作令号", false);
            return;
        }
        DataTable dt = containerBal.GetProductByProcess(txtTreeProcessNo.Text);
        getProductInfo.GetProductDDL.Visible = true;
        getProductInfo.GetProductNameOrTypeText.Visible = false;

        getProductInfo.GetProductDDL.DataTextField = "PRODUCTNAME";
        getProductInfo.GetProductDDL.DataValueField = "PRODUCTID";
        getProductInfo.GetProductDDL.DataSource = dt;
        getProductInfo.GetProductDDL.DataBind();

        getProductInfo.GetProductDDL.Items.Insert(0, "");
    }
    #endregion

}